package org.jeecg.common.system.base.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 通用 Controller
 *
 * @author chechen
 * @date 2021-11-20
 */
@NoArgsConstructor
public class GenericController<T, S extends IService<T>> {
    protected static final String PAGE = "分页列表查询";
    protected static final String LIST = "列表";
    protected static final String GET_BY_ID = "根据id获取";
    protected static final String ADD = "新增";
    protected static final String EDIT = "更新";
    protected static final String DELETE = "删除";
    protected static final String DELETE_BATCH = "批量删除";

    protected static final String OPERATE_SUCCESS = "操作成功";
    protected static final String ADD_SUCCESS = "新增成功";
    protected static final String EDIT_SUCCESS = "更新成功";
    protected static final String DELETE_SUCCESS = "删除成功";
    @Autowired(required = false)
    protected S service;

    protected static String dealWithBranchId() throws JeecgBootException {
        return dealWithBranchId((LoginUser) SecurityUtils.getSubject().getPrincipal(), null);
    }

    protected static String dealWithBranchId(String branchId) throws JeecgBootException {
        return dealWithBranchId((LoginUser) SecurityUtils.getSubject().getPrincipal(), branchId);
    }

    /**
     * 获取分站id
     *
     * @param loginUser 当前登陆用户对象
     * @param branchId  分站id
     * @return 分站id
     */
    protected static String dealWithBranchId(LoginUser loginUser, String branchId) throws JeecgBootException {
        if (StringUtils.isNotBlank(branchId))
            return branchId;

        if (CommonConstant.USER_TYPE_SYSTEM.equals(loginUser.getUserType()))
            return null;

        if (StringUtils.isNotBlank(loginUser.getSiteId()))
            return loginUser.getSiteId();

        throw new JeecgBootException("分站id数据缺失, 暂无数据");
    }


    /**
     * 获取当前登陆用户
     */
    protected static LoginUser getLoginUser() throws JeecgBootException {
        return (LoginUser) SecurityUtils.getSubject().getPrincipal();
    }

}
